package me.numark.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.BaseListFragment;
import me.numark.fragments.FeedFragment;
import me.numark.fragments.FriendsFragment;
import me.numark.model.BaseModel;
import me.numark.model.Tag;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.TinyDB;
import me.numark.view.SearchPopup;
import me.numark.view.TagCloudLinkView;
import me.numark.view.TagItem;

/**
 * Created by Evan on 15/8/10.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, TextWatcher, TextView.OnEditorActionListener, TagCloudLinkView.OnTagSelectListener, AdapterView.OnItemClickListener, SearchPopup.OnItemOnClickListener {
    @Bind(R.id.search_arrow)
    ImageView searchArrow;

    @Bind(R.id.search_edit)
    EditText searchEdit;

    @Bind(R.id.search_clear)
    ImageView searchClear;

    @Bind(R.id.fragments)
    View fragment;

    @Bind(R.id.empty_view)
    View emptyView;

    @Bind(R.id.tag_cloud)
    TagCloudLinkView tagCloud;

    @Bind(R.id.list)
    ListView mList;

    @Bind(android.R.id.empty)
    View listEmptyView;

    BaseListFragment[] fragments;

    int searchType = -1;

    private static final String HISTORY_KEY = "search_history";
    ArrayList<String> historyList = null;
    TinyDB mTinyDB;
    HistoryAdapter mHistoryAdapter;
    private SearchPopup searchPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_search;
        super.onCreate(null);

        fragments = new BaseListFragment[3];
        searchArrow.setOnClickListener(this);
        searchClear.setOnClickListener(this);
        searchEdit.addTextChangedListener(this);
        searchEdit.setOnEditorActionListener(this);
        if (Global.hotTags != null) {
            for (BaseModel tag : Global.hotTags) {
                tagCloud.add(new Tag((int) tag.id, tag.title));
            }
        }
        tagCloud.setOnTagSelectListener(this);
        mTinyDB = new TinyDB(this);
        historyList = mTinyDB.getListString(HISTORY_KEY);
        mHistoryAdapter = new HistoryAdapter();
        mList.setAdapter(mHistoryAdapter);
        mList.setEmptyView(listEmptyView);
        mList.setOnItemClickListener(this);
        switchSearchType(0);
        searchPopup = new SearchPopup(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        searchPopup.setItemOnClickListener(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTinyDB.putListString(HISTORY_KEY, historyList);
    }

    void switchSearchType(int type) {
        if (type == searchType)
            return;
        Fragment oldFragment = null;
        if (searchType >= 0)
            oldFragment = fragments[searchType];

        searchType = type;
        String hint = null;

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        BaseListFragment newFragment = fragments[searchType];
        if (newFragment == null) {
            switch (searchType) {
                case 0:
                    newFragment = FeedFragment.newInstance(Constants.FEEDTYPE_SEARCH_ALL, Global.getCurrentUid());
                    break;
                case 1:
                    newFragment = FriendsFragment.newInstance(Global.getCurrentUid(), false, FriendsFragment.TYPE_SEARCH);
                    break;
                case 2:
                    newFragment = FeedFragment.newInstance(Constants.FEEDTYPE_SEARCH_FOLLOW, Global.getCurrentUid());
                    break;
            }
            fragments[searchType] = newFragment;
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragments, newFragment, String.valueOf(searchType));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
        switch (searchType) {
            case 0:
                hint = getString(R.string.search_all);
                break;
            case 1:
                hint = getString(R.string.search_user);
                break;
            case 2:
                hint = getString(R.string.search_follow);
                break;
        }
        searchEdit.setHint(hint);

        String text = searchEdit.getText().toString();
        if (text.length() > 0) {
            newFragment.searchKey = text;
            final BaseListFragment finalNewFragment = newFragment;
            searchEdit.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finalNewFragment.refresh();
                }
            }, 300);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_arrow:
                showSearchType(v);
                break;
            case R.id.search_clear:
                searchEdit.setText("");
                break;
            case R.id.close_btn: {
                String text = (String) v.getTag();
                historyList.remove(text);
                mHistoryAdapter.notifyDataSetChanged();
            }
            break;
        }
    }

    void showSearchType(View v) {
        searchPopup.cleanTags();
        /*final AlertDialog.Builder ab = new AlertDialog.Builder(this);
        String[] items = new String[]{getString(R.string.search_all),
                getString(R.string.search_user),
                getString(R.string.search_follow)};
//        ab.setTitle("设置隐私状态");
        ab.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int type = which;
                switchSearchType(type);
            }
        });
        ab.setNegativeButton(android.R.string.cancel, null);
        ab.show();*/
        if (v.getId() == R.id.search_arrow) {
            searchPopup.addTags(new TagItem(getString(R.string.search_all)));
            searchPopup.addTags(new TagItem(getString(R.string.search_user)));
            searchPopup.addTags(new TagItem(getString(R.string.search_follow)));
            searchPopup.show(v);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchClear.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
        fragment.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    public void search(String text) {
        if (text.length() == 0) {
            fragment.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
            return;
        }
        emptyView.setVisibility(View.GONE);
        fragment.setVisibility(View.VISIBLE);
        BaseListFragment listFragment = fragments[searchType];
        listFragment.searchKey = text;
        listFragment.refresh();
        historyList.remove(text);
        historyList.add(0, text);
        mHistoryAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH||(event!=null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String text = v.getText().toString();
            search(text);
            return true;
        }
        return false;
    }

    @Override
    public void onTagSelected(Tag tag, int position) {
        Intent intent = new Intent(this, TagActivity.class);
        intent.putExtra(TagActivity.EXTRA_TAG, tag.getText());
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String text = historyList.get(position);
        searchEdit.setText(text);
        search(text);
    }

    @Override
    public void onItemClick(TagItem item, int position) {
        switchSearchType(position);
    }

    class HistoryAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (historyList == null)
                return 0;
            return historyList.size();
        }

        @Override
        public Object getItem(int position) {
            return historyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.history_list_item, parent, false);
            }
            TextView tv = (TextView) view.findViewById(R.id.text);
            String text = (String) getItem(position);
            View close = view.findViewById(R.id.close_btn);
            close.setTag(text);
            close.setOnClickListener(SearchActivity.this);
            tv.setText(text);
            return view;
        }
    }
}
